"""
@File    :   auto_import.py
@Time    :   2024/02/02 10:07:25
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   自动导入工具类
"""

import importlib
from pathlib import Path
from typing import Any, Iterator, Type

from fastapi import APIRouter, FastAPI

from src.models.models import OrmBase
from src.utils.path import PathUtil


class AutoImportUtil:
    """自动导入工具类"""

    @staticmethod
    def import_module(target_path: Path, root_path: Path) -> Any:
        """使用importlib导入

        Args:
            target_path (Path): 目标路径
            root_path (Path): 根路径
        """
        return importlib.import_module(
            str(target_path.relative_to(root_path)).replace(".py", "").replace("/", ".")
        )

    @staticmethod
    def auto_import_router(root_path: Path, router_path: Path, app: FastAPI):
        """自动导入路由

        Args:
            root_path (Path): 项目根目录路径
            router_path (Path): 路由文件夹路径
            app (FastAPI): Fastapi实例
        """
        # 遍历业务代码中的所有router.py文件
        router_rglob = PathUtil.rglob_pathlib(router_path, regexp_str="router.py")

        for router_inner_path in router_rglob:
            # 获取相对根目录的路由文件相对路径, 并进行转换
            dynamic_router = AutoImportUtil.import_module(router_inner_path, root_path)
            # 当找到APIRouter实例时自动注册
            if isinstance(getattr(dynamic_router, "router", None), APIRouter):
                app.include_router(dynamic_router.router)

        # 遍历业务代码中的所有router文件夹
        router_dir_rglob = PathUtil.rglob_pathlib(router_path, regexp_str="router")
        for router_dir_path in router_dir_rglob:
            if router_dir_path.is_dir():
                for router_member_path in PathUtil.rglob_pathlib(
                    router_dir_path, regexp_str="*.py"
                ):
                    # 获取相对根目录的路由文件相对路径, 并进行转换
                    dynamic_router_memver = AutoImportUtil.import_module(
                        router_member_path, root_path
                    )
                    # 当找到APIRouter实例时自动注册
                    if isinstance(
                        getattr(dynamic_router_memver, "router", None), APIRouter
                    ):
                        app.include_router(dynamic_router_memver.router)

    @staticmethod
    def auto_import_orm_model(
        root_path: Path, model_path: Path, regexp_str: str = "models.py"
    ) -> Iterator[tuple[str, Type[OrmBase]]]:  # type: ignore
        """自动导入orm模型

        Args:
            root_path (Path): 项目根目录路径
            model_path (Path): 模型文件夹路径
            regexp_str (str): 数据模型文件名称
        """

        # 遍历业务代码中的所有models.py文件
        models_rglob = PathUtil.rglob_pathlib(model_path, regexp_str=regexp_str)

        for model_path in models_rglob:
            # 获取相对根目录的路由文件相对路径, 并进行转换
            model_dir = AutoImportUtil.import_module(model_path, root_path)
            for var_name in dir(model_dir):
                # 排除以下划线开头的变量
                if not var_name.startswith("_"):
                    # 取出变量进行判断
                    model = getattr(model_dir, var_name)
                    # print(model != OrmBase, type(model), issubclass(model, OrmBase))
                    if (
                        model != OrmBase
                        and isinstance(model, type)
                        and issubclass(model, OrmBase)
                    ):
                        # 排除OrmBase数据模型基类
                        yield (var_name, model)
